import { computed, type ComputedRef, ref, type Slots, unref } from 'vue';
import type { BasicTableProps, FetchParams } from '../types/table';
import { isFunction, isObject } from 'lodash-es';
import type { Recordable } from '#/types/global';
import type { FormProps } from '#/components/BasicForm/src/types/form';

export function useVxeTableForm(
  propsRef: ComputedRef<BasicTableProps>,
  slots: Slots,
  fetch: (opt?: FetchParams | undefined) => Promise<void>,
  getLoading: ComputedRef<boolean | undefined>,
) {
  const show = ref(true);

  // 表单数据
  const getFormProps = computed((): Partial<FormProps> => {
    const { formConfig } = unref(propsRef);
    const { submitButtonOptions, resetButtonOptions } = formConfig || {};
    return {
      showAdvancedButton: true,
      baseColProps: {
        span: 6,
      },
      ...formConfig,
      submitButtonOptions: { loading: unref(getLoading), ...submitButtonOptions },
      resetButtonOptions: { loading: unref(getLoading), ...resetButtonOptions },
    };
  });

  // 表单插槽
  const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
    const keys = Object.keys(slots);
    return keys
      .map((item) => (item.startsWith('form-') ? item : null))
      .filter((item) => !!item) as string[];
  });
  // 表单插槽替换
  function replaceFormSlotKey(key: string) {
    if (!key) return '';
    return key?.replace?.(/form-/, '') ?? '';
  }
  // 表格插槽
  const getTableSlotKeys: ComputedRef<string[]> = computed(() => {
    const keys = Object.keys(slots);
    const dagta = keys
      .map((item) => (item.startsWith('table-') ? item : null))
      .filter((item) => !!item) as string[];
    // console.log("dagta", dagta)

    return dagta;
  });
  // 表格插槽替换
  function replaceTableSlotKey(key: string) {
    if (!key) return '';
    return key?.replace?.(/table-/, '') ?? '';
  }

  // 提交搜索
  function handleSearchInfoChange(info: Recordable) {
    const { handleSearchInfoFn } = unref(propsRef);
    if (handleSearchInfoFn && isFunction(handleSearchInfoFn)) {
      info = handleSearchInfoFn(info) || info;
    }
    fetch({ searchInfo: info, page: 1 });
  }

  function getShowForm() {
    return unref(show);
  }

  async function setShowForm(flag: boolean) {
    show.value = flag;
  }
  const getActionColumn = computed(() => {
    const { actionColumn } = unref(propsRef);
    // console.log('actionColumn', isObject(actionColumn));
    // console.log("isObject(actionColumn) ? actionColumn : false", isObject(actionColumn) ? actionColumn : false)

    return isObject(actionColumn) ? actionColumn : false;
  });

  return {
    getFormProps,
    replaceFormSlotKey,
    getFormSlotKeys,
    handleSearchInfoChange,
    getShowForm,
    setShowForm,
    getTableSlotKeys,
    replaceTableSlotKey,
    getActionColumn,
  };
}
